package com.lwl.zk;

import com.lwl.utils.Constants;
import org.I0Itec.zkclient.ZkClient;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
  zookeeper帮助类
 */
public class ZookeeperUtils {

    static ZkClient zkClient = null;

    /**
     * 创建session
     *
     * @return
     */
    public static ZkClient getSession() {
        if (zkClient == null) {
            zkClient = new ZkClient(Constants.ZK_SERVER, 5000, 5000);
        }
        return zkClient;
    }

    /**
     * 创建节点
     *
     * @param path
     * @return
     */
    public static boolean createNode(String path) {
        try {
            ZkClient zkClient = getSession();

            boolean exists = zkClient.exists(path);
            if (exists) {
                System.out.println(path + "节点已存在zookeeper中，忽略不创建。");
                return true;
            }

            zkClient.createPersistent(path, true);
        } catch (Exception e) {
            System.out.println("创建节点异常：" + e.getMessage());
            return false;
        }
        return true;
    }

    //写入数据
    public static void writeData(String path, Object content) {
        try {
            ZkClient zkClient = getSession();
            boolean exists = zkClient.exists(path);
            if (exists) {
                System.out.println(path + "节点写入数据：" + content);
                zkClient.writeData(path, content);
                return;
            }

            System.out.println(path + "节点不存在，写入数据失败");
        } catch (Exception e) {
            System.out.println("数据写入异常了");
        }
    }

}